package com.xidian.zhiancloud.controller.ledgerManagerment.targetAndSystem;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xidian.zhiancloud.constant.LedgerManagementConstant;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.SecuritySystemLedger;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.qo.ledgerManagerment.targetAndSystem.SecuritySystemLedgerQO;
import com.xidian.zhiancloud.service.ledgerManager.targerAndSystem.SecuritySystemLedgerService;
import com.xidian.zhiancloud.service.user.UserService;
import com.xidian.zhiancloud.service.user.usermanage.OrganizationService;
import com.xidian.zhiancloud.util.zyf.StringUtils;
import com.xidian.zhiancloud.vo.ledgerManagerment.targetAndSystem.SecuritySystemLedgerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 台账管理 目标职责与制度 安全制度台账
 *
 * @Author: Summerless
 * @Date: 2020/11/9 11:34
 */
@RestController
@RequestMapping("/SecuritySystemLedger")
public class SecuritySystemLedgerController extends BaseController {
    @Autowired
    private SecuritySystemLedgerService securitySystemLedgerService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationService organizationService;

    /**
     * 添加安全制度台账对象
     *
     * @param securitySystemLedger 安全制度台账对象
     * @return 是否添加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> add(SecuritySystemLedger securitySystemLedger) {
        securitySystemLedger.setCompanyId(getSessionUserCompanyId());
        securitySystemLedger.setCreateTime(new Date(System.currentTimeMillis()));
        Boolean ans = securitySystemLedgerService.save(securitySystemLedger);
        return ResultDTO.successOf(ans, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id获取安全制度台账对象
     *
     * @param id 安全制度台账对象的id
     * @return 安全制度台账对象
     */
    @GetMapping("/getById")
    public ResultDTO<SecuritySystemLedgerVO> getById(@RequestParam("id") Long id) {
        return ResultDTO.successOf(securitySystemLedgerService.getSecuritySystemLedgerVOById(id), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id列表删除安全制度台账对象
     *
     * @param ids 安全制度台账对象的id列表
     * @return 是否删除成功
     */
    @PostMapping("/deleteByIds")
    public ResultDTO<Boolean> deleteByIds(Long[] ids) {
        Boolean res = securitySystemLedgerService.removeByIds(Arrays.asList(ids));
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 修改安全制度台账对象
     *
     * @param securitySystemLedger 安全制度台账对象
     * @return 是否修改成功
     */
    @PostMapping("/patchById")
    public ResultDTO<Boolean> patchById(SecuritySystemLedger securitySystemLedger) {
        securitySystemLedger.setCompanyId(null);
        securitySystemLedger.setCreateTime(null);
        Boolean res = securitySystemLedgerService.updateById(securitySystemLedger);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 列表查询
     *
     * @param securitySystemLedgerQO 查询参数
     * @return 安全制度台账列表
     */
    @GetMapping("/getListByQO")
    public ResultDTO<IPage<SecuritySystemLedgerVO>> getList(SecuritySystemLedgerQO securitySystemLedgerQO) {
        if (securitySystemLedgerQO.getCurrent() == null || securitySystemLedgerQO.getSize() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        securitySystemLedgerQO.setCompanyId(getSessionUserCompanyId());
        return ResultDTO.successOf(securitySystemLedgerService.selectByQO(securitySystemLedgerQO), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, Long[] ids) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("安全制度台账导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<SecuritySystemLedger> list = securitySystemLedgerService.listByIds(Arrays.asList(ids));
        List<SecuritySystemLedgerVO> ans = new LinkedList<>();
        list.forEach(t -> {
            SecuritySystemLedgerVO vo = new SecuritySystemLedgerVO();
            BeanUtils.copyProperties(t, vo);
            Organization organization = organizationService.getById(vo.getOrganizationId());
            vo.setOrganizationName(organization == null ? "该部门已被删除" : organization.getName());
            if (vo.getApplicableOrganizationIds() != null) {
                List<Organization> organizations = organizationService.listByIds(Arrays.stream(vo.getApplicableOrganizationIds().split(",")).collect(Collectors.toList()));
                List<String> names = organizations.stream().map(Organization::getName).collect(Collectors.toList());
                vo.setApplicableOrganizationNames(StringUtils.concatStrings(names));
            }
            vo.setStatusName(LedgerManagementConstant.SecuritySystemStatus.get(vo.getStatus()));
            vo.setTypeName(LedgerManagementConstant.SecuritySystemType.get(vo.getType()));
            ans.add(vo);
        });
        System.out.println(list.size());
        EasyExcel.write(response.getOutputStream(), SecuritySystemLedgerVO.class).sheet("模板").doWrite(ans);
    }

    /**
     * 导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResultDTO<Boolean> upload(@RequestParam("file") MultipartFile file) throws IOException {
        List<SecuritySystemLedgerVO> list = EasyExcel.read(file.getInputStream()).head(SecuritySystemLedgerVO.class).sheet().doReadSync();
        List<SecuritySystemLedger> ans = new LinkedList<>();
        list.forEach(vo -> {
            SecuritySystemLedger ledger = new SecuritySystemLedger();
            BeanUtils.copyProperties(vo, ledger);
            ledger.setCreateTime(new Date(System.currentTimeMillis()));
            ledger.setCompanyId(getSessionUserCompanyId());
            String[] names = vo.getApplicableOrganizationNames().split(",");
            List<Long> ids = new LinkedList<>();
            for (String name : names) {
                LambdaQueryWrapper<Organization> organizationLambdaQueryWrapper = Wrappers.<Organization>lambdaQuery();
                organizationLambdaQueryWrapper.eq(Organization::getName, name);
                Organization organization = organizationService.getOne(organizationLambdaQueryWrapper);
                if (organization != null) {
                    ids.add(organization.getId());
                }
            }
            ledger.setApplicableOrganizationIds(StringUtils.concatLongs(ids));
            LambdaQueryWrapper<Organization> organizationLambdaQueryWrapper = Wrappers.<Organization>lambdaQuery();
            organizationLambdaQueryWrapper.eq(Organization::getName, vo.getOrganizationName());
            Organization organization = organizationService.getOne(organizationLambdaQueryWrapper);
            if (organization != null) {
                ledger.setOrganizationId(organization.getId());
            }
            ledger.setStatus(LedgerManagementConstant.SecuritySystemStatus.indexOf(vo.getStatusName()));
            ledger.setType(LedgerManagementConstant.SecuritySystemType.indexOf(vo.getTypeName()));
            ans.add(ledger);
        });
        Boolean res = securitySystemLedgerService.saveBatch(ans);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }
}
